package com.example.fw;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.example.tests.ContactData;
import com.example.utils.ListOf;
import com.example.utils.SortedListOf;

public class ContactHelper extends HelperBase{
	
	public static boolean CREATION = true;
	public static boolean MODIFICATION = false;

	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}
	
	private SortedListOf<ContactData> cachedContacts;
	
	public SortedListOf<ContactData> getContacts() {
		if (cachedContacts == null) {
			rebuildCache();
		}
		return cachedContacts;		
	}

	private void rebuildCache() {
		cachedContacts = new SortedListOf<ContactData>();
		manager.navigateTo().mainPage();
		List<WebElement> contactsRows = driver.findElements(By.xpath("//tr[@name='entry']"));
		for (WebElement contactRow : contactsRows) {
			String lastname = contactRow.findElement(By.xpath("td[2]")).getText();
			String home = contactRow.findElement(By.xpath("td[5]")).getText();
			cachedContacts.add(new ContactData().withLastname(lastname).withHome(home));
		}
	}

	public ListOf<ContactData> getHomePageContactsInfo() {
		manager.navigateTo().mainPage();
		String[] contact = new String[2];
		ListOf<ContactData> contacts = new ListOf<ContactData>();
		List<WebElement> contactsRows = driver.findElements(By.xpath("//tr[@name='entry']"));
		for (WebElement contactRow : contactsRows) {
			String firstname = contactRow.findElement(By.xpath("td[3]")).getText();
			String lastname = contactRow.findElement(By.xpath("td[2]")).getText();			
			if (firstname.length() != 0) {
				contact[0] = firstname;
				if (lastname.length() != 0) {
					contact[0] += " " + lastname;
				}
			} else if (lastname.length() != 0) {
				contact[0] = lastname;
			} else {
				contact[0] = null;
			}
			
			String home = contactRow.findElement(By.xpath("td[5]")).getText();
			if (home.length() != 0) {
				contact[1] = home;
			} else {
				contact[1] = null;
			}
			contacts.add(new ContactData().withLastname(contact[0]).withHome(contact[1]));
		}		
		return contacts;
	}

	public ListOf<ContactData> getPrintPhonesContactsInfo() {
		manager.navigateTo().printPhonesPage();
		String[] contact = new String[2];
		ListOf<ContactData> contacts = new ListOf<ContactData>();
		List<WebElement> contactsCells = driver.findElements(By.xpath("//td[@valign='top']"));
		for (WebElement contactCell : contactsCells) {
			String contactText = contactCell.getText();			
			if (contactText.length() > 1) {
				if (!contactText.startsWith(":")) {
					contact[0] = contactText.substring(0, contactText.indexOf(":"));
					contact[0] = contact[0].trim();
				} else {
					contact[0] = null;
				}
				
				if (contactText.indexOf(":\nH: ") != -1) {
					contactText = contactText.replaceFirst(".+\nH: ", "");
					if (contactText.indexOf("\n") != -1) {
						contact[1] = contactText.substring(0, contactText.indexOf("\n"));
					} else {
						contact[1] = contactText;
					}					
				} else if (contactText.indexOf(":\nM: ") != -1) {
					contactText = contactText.replaceFirst(".+\nM: ", "");
					if (contactText.indexOf("\n") != -1) {
						contact[1] = contactText.substring(0, contactText.indexOf("\n"));
					} else {
						contact[1] = contactText;
					}					
				} else if (contactText.indexOf(":\nW: ") != -1) {
					contactText = contactText.replaceFirst(".+\nW: ", "");
					if (contactText.indexOf("\n") != -1) {
						contact[1] = contactText.substring(0, contactText.indexOf("\n"));
					} else {
						contact[1] = contactText;
					}					
				} else {
					contact[1] = null;
				}
			} else {
				contact[0] = null;
				contact[1] = null;
			}
			contacts.add(new ContactData().withLastname(contact[0]).withHome(contact[1]));
		}		
		return contacts;
	}

	public ContactHelper createContact(ContactData contact) {
		initContactCreation();
		fillContactForm(contact, CREATION);
		submitContactCreation();
		returnToHomePage();
		rebuildCache();
		return this;
	}

	public ContactHelper modifyContact(int index, ContactData contact) {
		manager.navigateTo().mainPage();
		initContactModification(index);
		fillContactForm(contact, MODIFICATION);
		submitContactModification();
		returnToHomePage();
		rebuildCache();
		return this;	
	}

	public ContactHelper deleteContact(int index) {
		manager.navigateTo().mainPage();
		initContactModification(index);
		submitContactDeletion();
		returnToHomePage();
		rebuildCache();
		return this;
	}

	//------------------------------------------------------------------------------
	
	public ContactHelper initContactCreation() {		
		click(By.linkText("add new"));
		return this;
	}

	public ContactHelper fillContactForm(ContactData contact, boolean formType) {
		type(By.name("firstname"), contact.getFirstname());
		type(By.name("lastname"), contact.getLastname());
		type(By.name("address"), contact.getAddress());
		type(By.name("home"), contact.getHome());
		type(By.name("mobile"), contact.getMobile());
		type(By.name("work"), contact.getWork());
		type(By.name("email"), contact.getEmail());
		type(By.name("email2"), contact.getEmail2());
		selectByIndex(By.name("bday"), contact.getBday());
		selectByIndex(By.name("bmonth"), contact.getBmonth());
		type(By.name("byear"), contact.getByear());
		if (formType == CREATION) {
			int new_group = generateRandomSelectIndex(By.xpath("//select[@name='new_group']/option"));
			selectByIndex(By.name("new_group"), new_group);
		}
		type(By.name("address2"), contact.getAddress2());
		type(By.name("phone2"), contact.getPhone2());
		return this;
	}

	public ContactHelper submitContactCreation() {
		click(By.name("submit"));
		cachedContacts = null;
		return this;
	}

	public ContactHelper returnToHomePage() {
		click(By.linkText("home page"));
		return this;
	}

	public ContactHelper initContactModification(int index) {
		click(By.xpath("//tr[@name='entry'][" + (++index) + "]/td[7]/a/img"));
		return this;
	}

	public ContactHelper submitContactModification() {
		click(By.xpath("//input[@type='submit'][@value='Update']"));
		cachedContacts = null;
		return this;
	}

	public ContactHelper submitContactDeletion() {
		click(By.xpath("//input[@type='submit'][@value='Delete']"));
		cachedContacts = null;
		return this;
	}

}
